<template>
  <div class="role-manage">
    <!-- 角色列表卡片 -->
    <el-card class="role-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><UserFilled /></el-icon>
            角色管理
          </span>
          <el-button type="primary" @click="handleAddRole">
            <el-icon><Plus /></el-icon>新增角色
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="roleList"
        style="width: 100%"
        border
        highlight-current-row
        @current-change="handleCurrentChange"
      >
        <el-table-column type="index" width="60" align="center" label="序号" />
        <el-table-column prop="name" label="角色名称" min-width="120" />
        <el-table-column prop="code" label="角色标识" min-width="120" />
        <el-table-column prop="description" label="角色描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEditRole(row)">
              编辑
            </el-button>
            <el-button link type="primary" @click="handleConfigPermission(row)">
              权限配置
            </el-button>
            <el-button 
              link 
              type="danger" 
              :disabled="row.code === 'admin'"
              @click="handleDeleteRole(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="code">
          <el-input 
            v-model="formData.code" 
            placeholder="请输入角色标识"
            :disabled="formData.id"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 权限配置弹窗 -->
    <el-dialog
      v-model="permissionVisible"
      title="权限配置"
      width="900px"
      destroy-on-close
      class="permission-dialog"
    >
      <div class="permission-header">
        <span class="role-name">{{ currentRole?.name }}</span>
        <el-tag type="info">{{ currentRole?.code }}</el-tag>
      </div>
      
      <!-- 切换卡片 -->
      <div class="permission-tabs">
        <div 
          class="tab-item" 
          :class="{ active: activePermissionTab === 'data' }"
          @click="activePermissionTab = 'data'"
        >
          <el-icon><DataLine /></el-icon>
          数据权限控制
        </div>
        <div 
          class="tab-item" 
          :class="{ active: activePermissionTab === 'function' }"
          @click="activePermissionTab = 'function'"
        >
          <el-icon><Operation /></el-icon>
          功能权限配置
        </div>
      </div>

      <!-- 数据权限卡片 -->
      <el-card 
        v-show="activePermissionTab === 'data'"
        class="permission-card" 
        shadow="never"
      >
        <template #header>
          <div class="card-header">
            <span class="title">数据权限控制</span>
          </div>
        </template>
        
        <el-form :model="dataPermission" label-width="120px">
          <el-form-item label="数据权限范围">
            <el-radio-group v-model="dataPermission.scope">
              <el-radio-button label="1">全部数据</el-radio-button>
              <el-radio-button label="2">本部门数据</el-radio-button>
              <el-radio-button label="3">本部门及下级数据</el-radio-button>
              <el-radio-button label="4">仅本人数据</el-radio-button>
              <el-radio-button label="5">自定义数据</el-radio-button>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item v-if="dataPermission.scope === '5'" label="自定义部门">
            <el-select
              v-model="dataPermission.departments"
              multiple
              collapse-tags
              collapse-tags-tooltip
              placeholder="请选择部门"
              style="width: 100%"
            >
              <el-option
                v-for="item in departmentOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 功能权限卡片 -->
      <el-card 
        v-show="activePermissionTab === 'function'"
        class="permission-card permission-function-card" 
        shadow="never"
      >
        <template #header>
          <div class="card-header">
            <span class="title">功能权限配置</span>
          </div>
        </template>
        
        <!-- 搜索栏 -->
        <div class="permission-search">
          <el-input
            v-model="permissionSearch"
            placeholder="请输入权限名称或标识"
            clearable
            @keyup.enter="searchPermissions"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <!-- 权限列表 -->
        <el-table
          v-loading="permissionLoading"
          :data="permissionList"
          style="width: 100%"
          border
          :max-height="tableMaxHeight"
          @selection-change="handlePermissionSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="name" label="权限名称" min-width="150" />
          <el-table-column prop="code" label="权限标识" min-width="150" />
          <el-table-column prop="type" label="权限类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getPermissionTagType(row.type)">
                {{ getPermissionTypeName(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="权限描述" min-width="200" show-overflow-tooltip />
        </el-table>
        
        <!-- 分页 -->
        <div class="permission-pagination">
          <el-pagination
            v-model:current-page="permissionPage"
            v-model:page-size="permissionPageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="permissionTotal"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handlePermissionSizeChange"
            @current-change="handlePermissionCurrentChange"
          />
        </div>
      </el-card>
      
      <template #footer>
        <el-button @click="permissionVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermission">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, onUnmounted } from 'vue'
import { 
  UserFilled, Plus, Edit, Delete, Setting, Search,
  DataLine, Operation
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, TreeInstance } from 'element-plus'

// 角色列表数据
const loading = ref(false)
const roleList = ref([])
const currentRole = ref<any>(null)

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增角色')
const formRef = ref<FormInstance>()
const formData = reactive({
  id: '',
  name: '',
  code: '',
  description: '',
  status: 1
})

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9_]*$/, message: '以字母开头，只能包含字母、数字和下划线', trigger: 'blur' }
  ]
}

// 权限配置相关
const permissionVisible = ref(false)
const permissionLoading = ref(false)
const permissionSearch = ref('')
const permissionList = ref([])
const selectedPermissions = ref<any[]>([])
const permissionPage = ref(1)
const permissionPageSize = ref(10)
const permissionTotal = ref(0)

// 数据权限相关
const dataPermission = reactive({
  scope: '1',
  departments: []
})

// 部门选项
const departmentOptions = [
  { label: '技术部', value: 'tech' },
  { label: '产品部', value: 'product' },
  { label: '运营部', value: 'operation' },
  { label: '市场部', value: 'marketing' },
  { label: '销售部', value: 'sales' }
]

// 权限配置Tab
const activePermissionTab = ref('data')
const tableMaxHeight = ref(500)

// 计算表格最大高度
const calculateTableHeight = () => {
  nextTick(() => {
    const viewHeight = window.innerHeight
    // 减去其他元素的高度（对话框头部、角色信息、tab、搜索框、分页等）
    tableMaxHeight.value = viewHeight - 450
  })
}

// 获取角色列表
const getRoleList = async () => {
  loading.value = true
  try {
    // 模拟数据
    setTimeout(() => {
      roleList.value = [
        {
          id: 1,
          name: '超级管理员',
          code: 'admin',
          description: '系统最高权限',
          createTime: '2024-01-01 12:00:00',
          status: 1
        },
        {
          id: 2,
          name: '普通用户',
          code: 'user',
          description: '普通用户权限',
          createTime: '2024-01-01 12:00:00',
          status: 1
        }
      ]
      loading.value = false
    }, 500)
  } catch (error) {
    console.error(error)
    loading.value = false
  }
}

// 初始化
onMounted(() => {
  getRoleList()
  calculateTableHeight()
})

// 处理表格行选中
const handleCurrentChange = (row: any) => {
  currentRole.value = row
}

// 处理添加角色
const handleAddRole = () => {
  dialogTitle.value = '新增角色'
  dialogVisible.value = true
  Object.keys(formData).forEach(key => {
    formData[key] = key === 'status' ? 1 : ''
  })
}

// 处理编辑角色
const handleEditRole = (row: any) => {
  dialogTitle.value = '编辑角色'
  dialogVisible.value = true
  Object.assign(formData, row)
}

// 处理删除角色
const handleDeleteRole = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
      type: 'warning'
    })
    // TODO: 调用删除接口
    ElMessage.success('删除成功')
    getRoleList()
  } catch (error) {
    console.error(error)
  }
}

// 处理状态变更
const handleStatusChange = async (row: any) => {
  try {
    // TODO: 调用状态更新接口
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error(error)
    row.status = row.status === 1 ? 0 : 1
  }
}

// 获取权限列表
const getPermissionList = async () => {
  permissionLoading.value = true
  try {
    // 模拟数据
    setTimeout(() => {
      const list = Array(20).fill(null).map((_, index) => ({
        id: index + 1,
        name: `权限${index + 1}`,
        code: `permission:${index + 1}`,
        type: ['menu', 'button', 'api'][Math.floor(Math.random() * 3)],
        description: `这是权限${index + 1}的描述信息`
      }))
      permissionList.value = list
      permissionTotal.value = 100
      permissionLoading.value = false
    }, 500)
  } catch (error) {
    console.error(error)
    permissionLoading.value = false
  }
}

// 处理权限选择变更
const handlePermissionSelectionChange = (selection: any[]) => {
  selectedPermissions.value = selection
}

// 处理权限分页变更
const handlePermissionSizeChange = (size: number) => {
  permissionPageSize.value = size
  getPermissionList()
}

const handlePermissionCurrentChange = (page: number) => {
  permissionPage.value = page
  getPermissionList()
}

// 搜索权限
const searchPermissions = () => {
  permissionPage.value = 1
  getPermissionList()
}

// 获取权限类型标签样式
const getPermissionTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    menu: 'success',
    button: 'warning',
    api: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取权限类型名称
const getPermissionTypeName = (type: string) => {
  const typeMap: Record<string, string> = {
    menu: '菜单',
    button: '按钮',
    api: '接口'
  }
  return typeMap[type] || '未知'
}

// 处理权限配置
const handleConfigPermission = (row: any) => {
  currentRole.value = row
  permissionVisible.value = true
  // 重置数据权限
  dataPermission.scope = '1'
  dataPermission.departments = []
  activePermissionTab.value = 'data'
  getPermissionList()
  calculateTableHeight()
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    await formRef.value.validate()
    // TODO: 调用保存接口
    ElMessage.success('保存成功')
    dialogVisible.value = false
    getRoleList()
  } catch (error) {
    console.error(error)
  }
}

// 处理权限保存
const handleSavePermission = async () => {
  try {
    // TODO: 调用权限保存接口
    const permissionData = {
      roleId: currentRole.value?.id,
      permissions: selectedPermissions.value.map(item => item.id),
      dataPermission: {
        scope: dataPermission.scope,
        departments: dataPermission.departments
      }
    }
    ElMessage.success('权限配置保存成功')
    permissionVisible.value = false
  } catch (error) {
    console.error(error)
  }
}

// 监听窗口大小变化
window.addEventListener('resize', calculateTableHeight)

// 组件卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('resize', calculateTableHeight)
})
</script>

<style lang="scss" scoped>
.role-manage {
  .role-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title {
        font-size: 16px;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }
  }
  
  .permission-header {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 16px;
    
    .role-name {
      font-size: 16px;
      font-weight: 500;
    }
  }
  
  .permission-dialog {
    :deep(.el-dialog__body) {
      padding: 20px;
      max-height: calc(90vh - 120px);
      overflow-y: auto;
    }
  }
  
  .permission-tabs {
    display: flex;
    gap: 16px;
    margin-bottom: 16px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    padding-bottom: 16px;
    
    .tab-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 16px;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.3s;
      
      .el-icon {
        font-size: 16px;
      }
      
      &:hover {
        color: var(--el-color-primary);
        background: var(--el-color-primary-light-9);
      }
      
      &.active {
        color: var(--el-color-primary);
        background: var(--el-color-primary-light-9);
        font-weight: 500;
      }
    }
  }
  
  .permission-card {
    margin-bottom: 16px;
    transition: all 0.3s;
    
    :deep(.el-card__header) {
      padding: 12px 20px;
      border-bottom: 1px solid var(--el-border-color-lighter);
      
      .card-header {
        .title {
          font-size: 15px;
          font-weight: 500;
        }
      }
    }
    
    :deep(.el-card__body) {
      padding: 20px;
    }
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .el-radio-group {
    .el-radio-button__inner {
      padding: 8px 16px;
    }
  }
  
  .permission-search {
    margin-bottom: 16px;
  }
  
  .permission-pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
  
  :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
    
    th.el-table__cell {
      background-color: var(--el-fill-color-light);
      color: var(--el-text-color-regular);
      font-weight: 500;
    }
    
    .el-table__row {
      td.el-table__cell {
        padding: 12px 0;
      }
    }
  }
}

.permission-function-card {
  :deep(.el-table__body-wrapper) {
    overflow-y: auto;
    
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #ddd;
      border-radius: 3px;
      
      &:hover {
        background: #ccc;
      }
    }
  }
}
</style> 